package com.cwx.tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * Created by code on 17-8-30.
 */
@Component
public class CacheUtil {

    private Cache cache;

    @Autowired
    public CacheUtil(org.springframework.cache.CacheManager cacheManager){
        this.cache=cacheManager.getCache("phoneCache");
    }

    public Cache getCache() {
        return cache;
    }

    public void setCache(Cache cache) {
        this.cache = cache;
    }

    /*
 * 通过名称从缓存中获取数据
 */
    public Object getCacheElement(String cacheKey) throws Exception {
        Cache.ValueWrapper valueWrapper = cache.get(cacheKey);
        if (valueWrapper == null) {
            return null;
        }
        return valueWrapper.get();
    }

    /*
     * 将对象添加到缓存中
     */
    public void addToCache(String cacheKey, Object result) throws Exception {
        cache.put(cacheKey,result);
    }

    public void evict(String key){
        cache.evict(key);
    }

}
